package com.example.demoserver.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demoserver.util.JWTUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class Util {
    public static  String getNowTime(){
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatDateTime = now.format(formatter);
        return formatDateTime;
    }
    public static String getuserName(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    String token = cookie.getValue();
                    DecodedJWT verify = JWTUtil.verify(token);
                    String username = verify.getClaim("username").asString();
                    return username;
                }
            }
        }
        return null;

    }
    public static List<Map> compare(Object obj1, Object obj2) {
        try {
            Class<?> clazz = obj1.getClass();
            Field[] fields = clazz.getDeclaredFields();
            List<Map> list=new ArrayList<>();
            for (Field field : fields) {
                field.setAccessible(true);
                Object value1 = field.get(obj1);
                Object value2 = field.get(obj2);
                if (value1 == null && value2 == null) {
                    continue;
                } else if (value1 == null && value2 != null) {
                    //System.out.println("字段名：" + field.getName() + ", obj1: null, obj2: " + value2.toString());
                } else if (value1 != null && value2 == null) {
                    //System.out.println("字段名：" + field.getName() + ", obj1: " + value1.toString() + ", obj2: null");
                } else if (!value1.equals(value2)) {
                    //System.out.println("字段名：" + field.getName() + ", obj1: " + value1.toString() + ", obj2: " + value2.toString());
                    Map<String, Object> map = new HashMap<>();
                    map.put("field", field.getName());
                    map.put("value1", value1.toString());
                    map.put("value2", value2.toString());
                    list.add(map);
                }
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
